package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(value = "com.atguigu.gulimall.product.controller")
public class GulimallControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException m) {
        Map<String, String> map = new HashMap<>(16);
        m.getBindingResult().getFieldErrors().forEach(fieldError -> {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            map.put(field, message);
        });
        return R.error(BizCodeEnume.VATLD_EXCEPTION.getCode(), BizCodeEnume.VATLD_EXCEPTION.getMsg())
                .put("data", map);
    }

    @ExceptionHandler(RuntimeException.class)
    public R handRunTimeException(RuntimeException r) {
        log.error(r.getMessage(), r.getClass());
        return R.error(BizCodeEnume.RUNTIME_EXCEPTION.getCode(), BizCodeEnume.RUNTIME_EXCEPTION.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e.getClass());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
